package com.heima.behavior.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 使用过滤器获取用户信息，存入ThreadLocal
 */
@Component
@WebFilter(filterName = "appTokenFilter",urlPatterns = "/*")   // 声明为Filter
public class AppTokenFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            HttpServletResponse response = (HttpServletResponse)servletResponse;

            //从请求头获取userId
            String userId = request.getHeader("userId");

            //存入ThreadLocal中
            if(StringUtils.isNotEmpty(userId) && !userId.equals("0")){  //userId为0代表访客
                ApUser apUser = new ApUser();
                apUser.setId(Integer.valueOf(userId));
                ThreadLocalUtils.set(apUser);
            }
            //放行
            filterChain.doFilter(request,response);
        } finally {
            //清楚ThreadLocal线程数据
            ThreadLocalUtils.remove();
        }
    }
}
